package com.zxy.supplier_system.server.service

import com.zxy.supplier_system.server.controller.ProcurementSupplierStatisticController
import com.zxy.supplier_system.server.controller.ProcurementSupplierStatisticController.ProcurementPurchasePriceGroupByYearMonthResponse
import com.zxy.supplier_system.server.repository.ProcurementSupplierStatisticRepository
import org.springframework.stereotype.Service
import java.time.YearMonth

@Service
class ProcurementSupplierStatisticService(
    private val procurementSupplierStatisticRepository: ProcurementSupplierStatisticRepository,
    private val systemServiceService: SystemServiceService,
) {

    fun procurementPurchasePriceGroupByYearMonth(
        id: Int,
        request: ProcurementSupplierStatisticController.ProcurementPurchasePriceGroupByYearMonthRequest,
        timezone: String
    ): ProcurementPurchasePriceGroupByYearMonthResponse {
        val systemService = systemServiceService.getCurrentSystemService()
        val procurementFeeGroupByMonth =
            this.procurementSupplierStatisticRepository.getTotalPurchasePriceGroupByMonth(
                id,
                timezone,
                systemService,
                request
            )
        val returnFeeGroupByMonth = this.procurementSupplierStatisticRepository.getTotalReturnPriceGroupByMonth(
            id, timezone,
            systemService,
            request
        )
        val yearMonthList = mutableSetOf<YearMonth>().apply {
            addAll(procurementFeeGroupByMonth.map { YearMonth.of(it.year, it.month) })
            addAll(returnFeeGroupByMonth.map { YearMonth.of(it.year, it.month) })
        }
        val max = yearMonthList.max()
        val min = yearMonthList.min()
        val monthCount = max.year * 12 + max.monthValue - min.year*12 - min.monthValue
        val data = (1..monthCount + 1).map { i ->
            val yearMonth = min.plusMonths(i - 1L)
            ProcurementPurchasePriceGroupByYearMonthResponse.YearMonthData(
                yearMonth,
                procurementFeeGroupByMonth.find {
                    it.year == yearMonth.year && it.month == yearMonth.monthValue
                }?.price,
                returnFeeGroupByMonth.find {
                    it.year == yearMonth.year && it.month == yearMonth.monthValue
                }?.price
            )
        }

        return procurementFeeGroupByMonth.let {
            ProcurementPurchasePriceGroupByYearMonthResponse(data)
        }
    }
}